/**
 * Created by admin on 2017/9/13.
 */
define([
    "helpers/network",
    "models/commonStatus",
    "views/modules/popup",
    "views/modules/form",
    "views/modules/pager",
    "views/modules/table",
    "libs/editor/ueditor.all"
], function (Network, CommonStatus, PopupView, CommonForm, CommonPager, CommonTable) {
    var TYPE = "Slides";
    var id = "";
    var windowsId = id + "window";
    var formId = id + "form";
    var tableId = id + "table";
    var publishBtnId = id + "publishBtn";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var pageIndex = 1, pageCounts;
    var uEditor;
    var uEditorId = id + 'ueditor';
    var uEditorConfig = {
        UEDITOR_HOME_URL: "libs/editor/",
        serverUrl: Network.url.imgUploadUrl + "/file/ueditor.do?group=goodsDetail",
        initialFrameHeight: 420,
        autoHeightEnabled: false,
        toolbars: [
            ['fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'forecolor', 'backcolor', 'fontborder', 'strikethrough', '|', 'fontsize', 'lineheight', '|', 'link', '|', 'simpleupload', 'insertimage',]
        ]
    };

    var onTableReady = function (page) {
        var obj = {
            params: {
                // data: {
                //     name: searchForm[keywordsId] || undefined
                // },
                type: TYPE
            },
            page: page || 1,
            size: 20,
            sort: ["seq,desc", "creationTime,desc"]
        };
        Network.ajax("/ContentSlideView.queryAll.query", obj, function (ret) {
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        });
    };

    var closeWindow = function () {
        if ($$(windowsId)) {
            $$(windowsId).close();
        }
        if (uEditor) {
            uEditor.destroy();
        }
    };

    var onSubmit = function (itemId) {
        if (!$$(formId).validate()) {
            webix.message("信息填写有误, 请仔细录入...");
            return
        }
        var itemValues = $$(formId).getValues();
        var obj = {
            data: {
                id: itemId || undefined,
                title: itemValues.title,
                imageUrl: itemValues.imageUrl,
                linkInfo: {id: itemValues.linkInfo.id, data: {id: itemValues.goodsId}},
                seq: itemValues.seq
            }
        };

        Network.ajax(itemId ? "/ContentSlideTransactor.updateInfo.command" : "/ContentSlideTransactor.create.command", obj, function (ret) {
            closeWindow();
            onTableReady();
        })
    };

    var onWindowReady = function (item) {
        item = item || {};
        uEditor = UE.getEditor(uEditorId, uEditorConfig);
        uEditor.addListener('ready', function (state) {
            if (item.linkInfo && item.linkInfo.data.content) {
                uEditor.setContent(item.linkInfo.data.content.toApiUrlImageSrcContent());
            }
        });
    };

    var onPublish = function (item) {
        var action;
        if (item.status === "Published") action = "offline";
        if (item.status === "Offline") action = "publish";
        var obj = {
            data: {
                id: item.id
            }
        };
        Network.ajax("/ContentSlideTransactor." + action + ".command", obj, function (ret) {
            webix.message("操作成功");
            onTableReady();
        });
    };

    var showWindow = function (title, item) {
        item = item || {data: {}};
        PopupView(windowsId, title, {
            rows: [
                {
                    cols: [

                        {
                            view: "scrollview", scroll: "y", paddingY: 5, paddingX: 10,
                            body: {
                                rows: [
                                    {
                                        view: "form", borderless: true, id: formId,
                                        rules: {"seq": webix.rules.isNumber},
                                        elements: [
                                            {
                                                label: "标题", name: "title",
                                                view: "text", id: "title",
                                                required: true,
                                                value: item.title || ""
                                            },
                                            {
                                                label: "序号", name: "seq",
                                                view: "text", id: "seq",
                                                placeholer: "序号越大越靠前展示",
                                                required: true,
                                                value: item.seq || "0"
                                            },
                                            {label: "推荐图尺寸500*300", view: "label"},
                                            CommonForm.genSingleImgUploader("imageUrl", "缩略图", item["imageUrl"], true),
                                            {
                                                name: "linkInfo", view: "combo", label: "类型",
                                                value: item.linkInfo ? item.linkInfo.id : "",
                                                options: [{id: "PhoneCharges", value: "关联拼团商品"}, {
                                                    id: "ActualGoods",
                                                    value: "关联积分商品"
                                                }, {id: "Article", value: "关联图文"}]
                                            },
                                            {
                                                label: "商品id", name: "goodsId",
                                                view: "text", id: "goodsId",
                                                value: item.linkInfo ? item.linkInfo.data.id : "",
                                            }
                                            // {
                                            //     label: "链接", name: "link",
                                            //     view: "text", id: "link",
                                            //     required: true,
                                            //     value: item.data.link || ""
                                            // },
                                        ]
                                    }]
                            }

                        },
                        {
                            view: "scrollview", scroll: "y", paddingY: 5, paddingX: 10,
                            body: {
                                rows: [{
                                    name: "articleContent", id: "articleContent", borderless: true,
                                    template: function () {
                                        return "<div id='" + uEditorId + "'></div>"
                                    }
                                }]
                            }
                        }
                    ]
                },

                CommonForm.genSubmitButton(function () {
                    onSubmit(item.id)
                })
            ]
        }, 800, 550, function () {
            onWindowReady(item)
        }, closeWindow)
    };

    var genOperationFormUI = function () {
        return {
            view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
            cols: [
                {view: "label", label: "操作"},
                {
                    view: "button", label: "添加", width: 90,
                    // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                    click: function () {
                        showWindow("添加")
                    }
                },
                {
                    view: "button", label: "修改", width: 90,
                    // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                    click: function () {
                        var item = $$(tableId).getSelectedItem();
                        if (item) showWindow("修改", item)

                    }
                },
                {
                    id: publishBtnId, view: "button", value: "发布/撤回",
                    // hidden: Authority.hasNoAuth("GOODS_ONLINE"),
                    width: 90,
                    click: function () {
                        var item = $$(tableId).getSelectedItem();
                        if (item) onPublish(item)
                    }
                }
            ]
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row", data: [],
            ready: onTableReady,
            on: {
                onItemClick: function (id) {
                    var item = this.getItem(id);
                    if (item.status.id === "Offline") {
                        $$(publishBtnId).setValue("发布");
                    } else if (item.status.id === "Published") {
                        $$(publishBtnId).setValue("撤回");
                    }
                    $$(publishBtnId).refresh();
                }
            },
            columns: [
                {
                    id: "id", header: "ID"
                },
                {
                    id: "title", header: "标题", fillspace: true
                },
                {
                    id: "seq", header: "序号", fillspace: true
                },
                {
                    id: "status", header: "状态"
                }
            ]
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            type: "clean", padding: 10,
            rows: [
                // genSearchFormUI(),
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };

});